package com.shengyijie.activity.usertab;
  
 
import java.util.LinkedList;

import org.apache.http.HttpResponse;
 
import com.shengyijie.activity.MainActivity;
import com.shengyijie.activity.R;         
import com.shengyijie.activity.StartActivity;
import com.shengyijie.activity.UserTabActivity;
import com.shengyijie.activity.commen.PushDetailActivity; 
import com.shengyijie.activity.tab.AboutActivity;
import com.shengyijie.adapter.view.AlertBox;
import com.shengyijie.adapter.view.AlertBox.OnCanceledListener;
import com.shengyijie.adapter.view.PullToRefreshListView;
import com.shengyijie.adapter.view.PullToRefreshListView.OnRefreshListener;
import com.shengyijie.adapter.viewadapter.MessageListAdapter;
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.http.HttpConnectApi;
import com.shengyijie.model.json.JsonParser;
import com.shengyijie.model.object.Listobject.PushMessageList;  
import com.shengyijie.model.object.baseobject.PushMessage;
import com.shengyijie.util.DataStore;
import com.shengyijie.util.Utility;

import android.app.Activity;  
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent; 
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.AdapterView; 
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class UserCenterActivity extends Activity implements OnClickListener{ 
	 
	public Task task;
	private HttpConnectApi httpConnect;
	private PullToRefreshListView listView;
	private TextView tv_no;
	private MessageListAdapter listAdapter;
	//int maxId=0;
	
	public LinkedList<PushMessage> messageList=new LinkedList<PushMessage>(); 
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.usercenter); 
         initView();
         getPushMessage();
    }  
    public void initView(){
    	TextView title=(TextView) UserTabActivity.group.findViewById(R.id.title); 
    	title.setText("我的生意街");
    	Button refresh=(Button) UserTabActivity.group.findViewById(R.id.right);
    	refresh.setVisibility(View.VISIBLE); 
    	refresh.setOnClickListener(this);
    	listView=(PullToRefreshListView) this.findViewById(R.id.messagelist); 
   	    listView.setOnItemClickListener(itemClickListener);
   	    listView.setOnRefreshListener(new OnRefreshListener() {
         @Override
         public void onRefresh() {
        	 preTask=1;
        	 task=new Task();  
    	     task.execute(TASK_LOAD); 
         }
       });
   	 
   	    
   	    
   	    tv_no=(TextView) this.findViewById(R.id.no);
   	    tv_no.setVisibility(View.INVISIBLE); 
   	     
    }
    int preTask=0;
    public void getPushMessage(){
    	listView.postDelayed(new Runnable() {  
             public void run() {  
            	 mypDialog=new AlertBox(UserCenterActivity.this,UserCenterActivity.this,findViewById(R.id.user)); 
            	 mypDialog.setCompletedListener(new OnCanceledListener(){ 
 					@Override
 					public void onCanceled() { 
 						if(task.getStatus()==AsyncTask.Status.RUNNING){
 				    		 task.cancel(true); 
 						  }
 					}});
            	 preTask=0;
            	 task=new Task();  
        	     task.execute(TASK_LOAD); 
             }  
         },1); 
    }
    public boolean onKeyDown(int keyCode,KeyEvent event) {   
	    if (keyCode == KeyEvent.KEYCODE_BACK) { 
	    	
				 new AlertDialog.Builder(this).setTitle("提示")
				 .setMessage("确定退出？")
				 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) { 
						Utility.clearUserSession(UserCenterActivity.this);
						UserCenterActivity.this.finish();
						MainActivity.tabhost.setCurrentTab(0);
					}
				  })
				  .setNegativeButton("取消", new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, int whichButton) {
					     }
				  })
				  .show();
	    	
	         return true;   
	     } else
	         return super.onKeyDown(keyCode,event);   
	 }
     
    String push_id; 
	 public OnItemClickListener itemClickListener = new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try{ 
					
					ContextApplication.pushMessage=messageList.get(position-1);
					changeToPushActivity();
//					PushMessage content=(PushMessage)parent.getItemAtPosition(position);  
//					push_id=content.getID();
//					preTask=0;
//			    	task=new Task();  
//	   		        task.execute(TASK_LOAD_PUSH); 
					 
				}catch(Exception e){}
			}
	    };
    boolean isRe=false;
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		 switch(v.getId()){ 
             case R.id.right: 
            	 preTask=0;
            	 isRe=true;
            	 task=new Task();  
        	     task.execute(TASK_LOAD); 
            	 break;
		 }
	}
	boolean isFirst=true;
	public void setAdapter(){ 
		messageList.clear();
			for(int i=0;i<pushMessageList.getCount();i++){
				messageList.add(pushMessageList.getItem(i)); 
			} 
			listAdapter = new MessageListAdapter(this, messageList, listView);  
	
		 
	}
	
	PushMessageList pushMessageList;
    public String doGetPushMessage(){
    	  
    	String result="message_fail";
        httpConnect=HttpConnectApi.getInstance();
        try {  
            HttpResponse response=httpConnect.getFindManage(ContextApplication.user.getSession_ID(),"0,15");
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    pushMessageList=jsonParser.getPushMessage(response);
           	    if(pushMessageList!=null){
           	    	if(pushMessageList.getCount()>0){
           	    	    setAdapter();
           	    	    result="message_ok";
           	    	}else if(pushMessageList.getCount()==0)
           	    		result="message_0";
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
     
    public String doGetMessageDetail(){
    	String result="md_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getMessageDetail(ContextApplication.user.getSession_ID(),push_id);
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    ContextApplication.pushMessage=jsonParser.getMessageDetail(response);
           	    if( ContextApplication.pushMessage!=null){ 
           	    	result="md_ok"; 
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    
    public void changeToPushActivity(){
		 Intent intent=new Intent();
		 intent.setClass(this, PushDetailActivity.class);
		 this.startActivityForResult(intent,1);
   }
    
	
	 private AlertBox mypDialog; 
	 private final static int ALERT_LOADING=1; 
	 private final static int RESULT_LOAD_OK=2;
	 private final static int RESULT_LOAD_FAIL=3;
	 private final static int RESULT_LOAD_0=4; 
	 
	 private final static int RESULT_LOAD_PUSHDETAIL_OK=5;
	 private final static int RESULT_LOAD_PUSHDETAIL_FAIL=6;
	 
	 private final static String TASK_LOAD_PUSH="loaditem";    
	    
	 private final static String TASK_LOAD="load";   
	 private final Handler handler = new Handler(Looper.getMainLooper()) {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			 	switch (msg.what) { 
				   case ALERT_LOADING:
					    //mypDialog.setMessage("正在载入中...");
					    mypDialog.show();
					    break;
				   case RESULT_LOAD_FAIL:
					   try{
						   if(isFirst||isRe){
							   mypDialog.dismiss(); 
							   isFirst=false;
							   isRe=false;
						   }else{
							   listView.onRefreshComplete();
						   } 
					      Toast.makeText(UserCenterActivity.this, "对不起，载入失败", Toast.LENGTH_SHORT).show();
					    }catch(Exception e){}
					     break;
				   case RESULT_LOAD_0:
					    try{
					    	if(isFirst||isRe){
								   mypDialog.dismiss(); 
								   isFirst=false;
								   isRe=false;
							   }else{
								   listView.onRefreshComplete();
							   }
						     Toast.makeText(UserCenterActivity.this, "对不起，没有新的消息了", Toast.LENGTH_SHORT).show();
						      
			 	         }catch(Exception e){}
					     break; 
				    
                   case RESULT_LOAD_OK:
                   	     try{
                   	    	if(isFirst||isRe){
 							   mypDialog.dismiss(); 
 							   isFirst=false;
 							   isRe=false;
 							   listView.setAdapter(listAdapter);
 						   }else{
 							   listView.onRefreshComplete();
 						   }
	                    	 
                   	     }catch(Exception e){}
					     break; 
                   case RESULT_LOAD_PUSHDETAIL_OK:
                	     mypDialog.dismiss(); 
                	     changeToPushActivity();
					     break; 
                   case RESULT_LOAD_PUSHDETAIL_FAIL:
					     mypDialog.dismiss(); 
					     Toast.makeText(UserCenterActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					     break; 
				}
			}
		};
		
		
	private class Task extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			if(params[0].equals(TASK_LOAD)){
				return doGetPushMessage();
			}else if(params[0].equals(TASK_LOAD_PUSH)){
				return doGetMessageDetail();
			}else
			    return ""; 
		} 
		@Override
		protected void onPostExecute(String result) {				
			super.onPostExecute(result);

			if(result.equals("message_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("message_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_OK;
				handler.sendMessage(msg);
			}else if(result.equals("message_0")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_0;
				handler.sendMessage(msg);
			}else if(result.equals("md_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_PUSHDETAIL_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("md_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_PUSHDETAIL_OK;
				handler.sendMessage(msg);
			} 
		} 
		@Override
		protected void onPreExecute() { 
			super.onPreExecute(); 
			if(preTask==0){
				Message msg = Message.obtain();
				msg.what = ALERT_LOADING;
				handler.sendMessage(msg);
			}
			
			 
		} 
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
	}
    
}